package com.mixsmart.spellsql.where.exp;

import com.mixsmart.utils.StringUtils;

public abstract class AbstractLikeExpression extends AbstractExpression {

    private String fieldName;
    private Object value;
    private String fieldVarName;
    
    public AbstractLikeExpression(String fieldName, Object value) {
        this.fieldName = fieldName;
        this.fieldVarName = fieldName;
        this.value = value;
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public String build() {
        String valueStr = StringUtils.handleNull(value);
        String leftValue = "";
        String rightValue = "";
        String leftLike = StringUtils.handleNull(getLeftLike());
        String rightLike = StringUtils.handleNull(getRightLike());
        String argName = super.getArgKey(fieldVarName);
        if (StringUtils.isNotEmpty(valueStr)) {
            // 判断值是否是一个常量
            if (valueStr.startsWith("'") && valueStr.endsWith("'")) {
                valueStr = valueStr.replace("'", "");
                super.addParameter(argName, leftLike + valueStr + rightLike);
            } else {
                leftValue = super.getLeftConstantValue(valueStr);
                rightValue = super.getRightConstantValue(valueStr);
                valueStr = super.removeSingleQuoteValue(valueStr);
                super.addParameter(argName, leftLike + leftValue + valueStr + rightValue + rightLike);
            }
        } else {
            super.addParameter(argName, leftLike + valueStr + rightLike);
        }
        return fieldName + " like :" + argName;
    }
    
    /**
     * 左Like，具体由子类实现
     * @return 返回左边like标识；如："%"
     */
    protected abstract String getLeftLike();
    
    /**
     * 右Like，具体由子类实现
     * @return 返回右边like标识；如："%"
     */
    protected abstract String getRightLike();

    @Override
    public String getFieldName() {
        return fieldName;
    }

    @Override
    public void setFieldVarName(String fieldVarName) {
        this.fieldVarName = fieldVarName;
    }

    @Override
    public String getFieldVarName() {
        return fieldVarName;
    }
}
